package leetcode.剑指offer.后40;

import org.junit.Test;

/**
 * @author :songyaozhang
 * @date :Created 2021/7/31 12:21
 * @description :https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/
 */
public class 剑指_43_1n整数中1出现的次数 {
    @Test
    public void test() {
        Solution solution = new Solution();
        System.out.println(solution.countDigitOne(12));
        System.out.println(solution.countDigitOne(Integer.MAX_VALUE));
    }

    class Solution {
        //32104
        public int countDigitOne(int n) {
            int digit = 1;
            int res = 0;
            int high = n / 10;
            int cur = n % 10;
            int low = 0;
            while (high != 0 || cur != 0) {
                if (cur == 0) res += high * digit;
                else if (cur == 1) res += high * digit + low + 1;
                else res += (high + 1) * digit;
                low += cur * digit;
                cur = high % 10;
                high /= 10;
                digit *= 10;
            }
            return res;
        }

    }

}
